<?php

namespace App\Admin\Actions\Grid;

use App\Wen\Utils\CollecterUtils;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BatchCollecterpublishAction extends BatchAction
{
    /**
     * @return string
     */
    protected $title = '发布';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $ids = $this->getKey();

        foreach ($ids as $id){
            DB::transaction(function () use ($id){
                DB::beginTransaction();
                try {
                    // todo:
                    CollecterUtils::publish($id);
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return $this->response()
                        ->error($e->getMessage())->refresh();
                }
            });
        }

        return $this->response()
            ->success('已提交给发布程序: '.json_encode($this->getKey()))->refresh();
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认发布?'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}
